import { Injectable } from '@angular/core';
import { Http } from "@angular/http";
import { ReplaySubject } from "rxjs/ReplaySubject";
import { STOCKURL } from "./config";

// 本地搜索是否启用
export const LOCALSEARCH = "enable";  // disable

// 股票代码的搜索结果
export type SearchStockClass = {
  abbr: string,
  market: string,
  name: string,
  symbol: string
};

@Injectable()
export class SummaryNameService {
  summaryNameSub = new ReplaySubject(1);

  constructor(private http: Http) {
    this.getSummaryName().subscribe(res => {
      // console.debug('%c LocalDB: ', 'color:#F09', res);
      this.summaryNameSub.next(res);
    }, err => {
      console.warn("summary name err: ", err);
      let res = localStorage.getItem("zytg_stock_names")
      res = res ? JSON.parse(res) : []
      this.summaryNameSub.next(res);
    });
  }

  getSummaryName() {
    return this.http.get(`${STOCKURL}/api/v2/sc/stocks/search/names`, { withCredentials: true })
    .map(res => {
      res = res.json()
      if (res.data) return res.data
      return res
    })
    .do( data => {
      if (data.length) {
        try {
          localStorage.setItem("zytg_stock_names", JSON.stringify(data))
        } catch (err) {
          console.warn("stock name cache failed", err)
        }
      }
    })    
  }
}